import RecallService_pb2
import RecallService_pb2_grpc
import time
from rec.update_recall import updateRecall
from concurrent import futures
import grpc

_ONE_DAY_IN_SERVICE = 60 * 60 * 24
IP = "[::]:50051"


# python服务的具体实现类
class service(RecallService_pb2_grpc.RpcRecService):

    # 根据用户ID生成用户画像召回集
    def genUserProfileRecallByUid(self, request, context):
        ur = updateRecall()
        uid = int(request.uid)
        ur.update_profile_recall_byuid(uid)
        print("生成用户ID={msg}的特征召回集完成".format(msg=uid))
        return RecallService_pb2.RecReply(message="更新用户ID= {msg} 的特征召回集完成".format(msg=uid))

    # 更新用户历史的召回集
    def updateUserHistoryRecall(self, request, context):
        ur = updateRecall()
        uid = int(request.uid)
        ur.update_user_history_recall()
        print("更新用户历史召回集完成")
        return RecallService_pb2.RecReply(message='更新用户历史召回集完成 : {msg}'.format(msg=uid))

    # 更新存在用户画像的用户的召回集
    def updateUserProfileRecall(self, request, context):
        ur = updateRecall()
        uid = int(request.uid)
        ur.update_profile_reacall()
        print("更新所有用户的特征召回集完成")
        return RecallService_pb2.RecReply(message='更新所有用户的特征召回集完成 : {msg}'.format(msg=uid))


def serve():
    grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=4))
    RecallService_pb2_grpc.add_RpcRecServiceServicer_to_server(service(), grpcServer)
    grpcServer.add_insecure_port(IP)
    grpcServer.start()
    print("推荐接口服务开启完成")

    try:
        while True:
            time.sleep(_ONE_DAY_IN_SERVICE)
    except KeyboardInterrupt:
        grpcServer.stop(0)


if __name__ == '__main__':
    serve()
